<template>
    <a-modal :open="visible" :title="title" width="770px" forceRender :destroyOnClose="true" :maskClosable="false"
        @cancel="onClose">
        <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }">
            <a-form-item label="协议名称" name="blagreementname">
                <a-input :disabled="canEdit" v-model:value="form.blagreementname" placeholder="请输入协议名称" />
            </a-form-item>
            <a-form-item label="协议编号" name="blagreementnum">
                <a-input :disabled="true" v-model:value="form.blprojectnum" placeholder="协议编号" />
            </a-form-item>
            <a-form-item label="协议所属项目" name="blprojectnum">
                <a-select :disabled="canEdit" v-model:value="form.blprojectnum" :allowClear="true" size="Middle"
                    style="width: 100%" @change="onChangePro" :options="options" placeholder="请选择执行单位"></a-select>
            </a-form-item>
            <a-form-item label="金额" name="blmoney">
                <a-input-number :disabled="canEdit" placeholder="请输入金额" style="width: 100%" v-model:value="form.blmoney"
                    addon-after="元"></a-input-number>
            </a-form-item>
            <a-form-item label="期数" name="blcycle">
                <a-input-number :disabled="canEdit" :min="1" style="width: 100%" v-model:value="form.blcycle"
                    placeholder="请输入期数"></a-input-number>
            </a-form-item>
            <a-form-item label="捐赠方" name="bldonorid">
                <a-select :disabled="canEdit" v-model:value="form.bldonorid" :allowClear="true" size="Middle"
                    style="width: 100%" @change="onChangeBldonorid" :options="optionsBldonorid"
                    placeholder="请选择捐赠方"></a-select>
            </a-form-item>
            <a-form-item label="联系方" name="bllinkmanid">
                <a-select :disabled="canEdit" v-model:value="form.bllinkmanid" :allowClear="true" size="Middle"
                    style="width: 100%" @change="onChangeContact" :options="optionsContact"
                    placeholder="请选择项目联系方"></a-select>
            </a-form-item>
            <a-form-item label="执行方" name="blfollowid">
                <a-select :disabled="canEdit" v-model:value="form.blfollowid" :allowClear="true" size="Middle"
                    style="width: 100%" @change="onChangeLeader" :options="optionsLeader"
                    placeholder="请选择执行方"></a-select>
            </a-form-item>
            <a-form-item label="协议签订日期" name="blregist">
                <a-date-picker :disabled="canEdit" :valueFormat="'YYYY-MM-DD'" ; style="width: 100%;"
                    placeholder="请选择协议签订日期" v-model:value="form.blregist" />
            </a-form-item>
            <a-form-item label="是否限定" name="blproperty">
                <a-select :disabled="canEdit" v-model:value="form.blproperty" style="width: 100%" placeholder="请选择是否限定"
                    :allowClear="true" size="Middle" @change="changeBlproperty">
                    <a-select-option :value="0">非限定</a-select-option>
                    <a-select-option :value="1">限定</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item label="说明" name="bldescription">
                <a-textarea :disabled="canEdit" v-model:value.trim="form.bldescription" placeholder="请输入说明"
                    :auto-size="{ minRows: 2, maxRows: 5 }" />
            </a-form-item>
            <a-form-item label="协议生效时间及金额
            " name="effect">
                <a-row>

                    <a-space v-for="(item, index) in form.effect" style="display: flex;width:100%" align="baseline">
                        <a-col :span="24">
                            <a-form-item label="日期" :name="`bleffective${index}`">
                                <a-date-picker :rules="{
                                    required: true,
                                    message: '请选择年份',
                                  }" :disabled="canEdit" :valueFormat="'YYYY-MM-DD'" ; style="width: 180px"
                                    placeholder="请选择年份" v-model:value="item.bleffective" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item label="金额" :name="`blrelmoney${index}`">
                                <a-input-number :disabled="canEdit" style="width: 100%" v-model:value="item.blrelmoney"
                                    placeholder="请输入金额" addon-after="元"></a-input-number>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24" v-show="!canEdit">
                            <MinusCircleOutlined @click="removeUser(item,1)" />
                            <PlusCircleOutlined style="margin-left: 15px;" @click="addUser(1)" />
                        </a-col>
                    </a-space>

                </a-row>
            </a-form-item>
            <a-form-item label="到账时间及金额
            " name="amount">
                <a-row>
                    <a-space v-for="(item, index) in form.amount" style="display: flex;width:100%" align="baseline">
                        <a-col :span="24">
                            <a-form-item label="日期" :name="`blamountdate${index}`">
                                <a-date-picker :disabled="canEdit" :valueFormat="'YYYY-MM-DD'" ; style="width: 180px"
                                    placeholder="请选择日期" v-model:value="item.blamountdate" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item label="金额" :name="`blamountmoney${index}`">
                                <a-input-number :disabled="canEdit" style="width: 100%"
                                    v-model:value="item.blamountmoney" placeholder="请输入到账金额"
                                    addon-after="元"></a-input-number>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24" v-show="!canEdit">
                            <MinusCircleOutlined @click="removeUser(item,2)" />
                            <PlusCircleOutlined style="margin-left: 15px;" @click="addUser(2)" />
                        </a-col>
                    </a-space>
                </a-row>
            </a-form-item>
            <a-form-item label="各部门分配金额" name="dept">
                <a-row style="width: 100%;">
                    <a-space v-for="(item, index) in form.dept" style="display: flex;width:100%" align="baseline">
                        <a-col :span="24">
                            <a-form-item label="部门" :name="`bldeptnum${index}`">
                                <a-select :disabled="canEdit" v-model:value="item.bldeptnum" :allowClear="true"
                                    size="Middle" style="width: 180px" @change="onChangeDept($event, index)"
                                    :options="optionsDept" placeholder="请选择部门"></a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item label="金额" :name="`blproposedmoney${index}`">
                                <a-input-number :disabled="canEdit" style="width: 100%"
                                    v-model:value="item.blproposedmoney" placeholder="请输入金额"
                                    addon-after="元"></a-input-number>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24" v-show="!canEdit">
                            <MinusCircleOutlined @click="removeUser(item,3)" />
                            <PlusCircleOutlined style="margin-left: 15px;" @click="addUser(3)" />
                        </a-col>
                    </a-space>
                </a-row>
            </a-form-item>
            <a-form-item label="资金用途" name="blusenum">
                <a-checkbox-group :disabled="canEdit" @change="onChangeUse" v-model:value="form.blusenum"
                    name="checkboxgroup" :options="plainOptions" />
            </a-form-item>
            <a-form-item label="协议上传" name="fileList" v-show="!canEdit">
                <a-upload accept=".pdf,.docx,.doc" :before-upload="beforeUpload" @change="handleChange"
                    :remove="handleRemove" :multiple="false" v-model:file-list="form.fileList">
                    <a-button :disabled="canEdit">
                        <a-icon type="upload" /> 选择文件
                    </a-button>
                </a-upload>
            </a-form-item>
            <a-form-item label="协议展示" name="bldescription" v-show="canEdit || form.blagreementid">
                <a-list item-layout="horizontal" :data-source="typeOneArray">
                    <template #renderItem="{ item }">
                        <a-list-item>
                            <a-list-item-meta>
                                <template #title>
                                    <a :href="item.blpersonphotopath" target="_blank" style="color: #1677ff;">{{
                                        item.blpersonphotopath.split('/').pop() }}</a>
                                </template>
                            </a-list-item-meta>
                        </a-list-item>
                    </template>
                </a-list>
            </a-form-item>
        </a-form>
        <template #footer>
            <a-space>
                <a-button @click="onClose" v-show="!canEdit">取消</a-button>
                <a-button type="primary" v-show="!canEdit" v-throttle @click="onSubmit">保存</a-button>
            </a-space>
        </template>
    </a-modal>
</template>

<script setup>
    import { message } from 'ant-design-vue';
    import pcaa from 'china-area-data';
    import _ from 'lodash';
    import { nextTick, reactive, ref, defineProps, onMounted, computed, watchEffect, watch } from 'vue';
    import { ProNameApi } from '/@/api/basicManage/Promanage/ProName-api';
    import { employeeApi } from '/src/api/system/employee-api';
    import { ProLeaderApi } from '/src/api/basicManage/DonationManage/ProLeader-api';
    import { AgreeApi } from '/src/api/basicManage/Promanage/Agree-api.js';
    import AreaCascader from '/@/components/framework/area-cascader/index.vue';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import Upload from '/@/components/support/file-upload/index.vue';
    import { regular } from '/@/constants/regular-const';
    import { useUserStore } from '/@/store/modules/system/user';
    import { smartSentry } from '/@/lib/smart-sentry';
    import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue';
    defineExpose({
        showModal,
        showViewModal
    });

    const emit = defineEmits(['refresh']);
    // ====== 标题===============
    const title = ref("");
    // 是否可编写
    const canEdit = ref(false);
    // 是否上传
    const isUpdate = ref(false)
    // --------------------- modal 显示与隐藏 ---------------------
    // 是否展示
    const visible = ref(false);
    function showModal(data) {
        Object.assign(form, formDefault);
        console.log('form:', form)
        if (data.blagreementid && !_.isEmpty(data)) {
            Object.assign(form, data);
            if (form.blusenum) {
                form.blusenum = form.blusenum.split(',').filter(item => item !== '');
            }
            // 协议
            if (form.bleffective) {
                let ffective = form.bleffective.split(',').filter(item => item !== '');
                let blrelmoney = form.blrelmoney.split(',').filter(item => item !== '');
            }
            let ffective = form.bleffective.split(',').filter(item => item !== '');
            let blrelmoney = form.blrelmoney.split(',').filter(item => item !== '');
            // 使用 forEach 方法将分割后的值赋给 effect 数组中每个对象的 bleffective 属性
            form.effect = form.effect.filter(item => item.bleffective !== undefined);
            ffective.forEach((item, index) => {
                form.effect.push({
                    bleffective: item,
                    blrelmoney: blrelmoney[index] || '' // 使用 || 运算符确保 blrelmoney[index] 有值，否则为 ''
                });
            });
            // 到账
            let blamountdate = form.blamountdate.split(',').filter(item => item !== '');
            let blamountmoney = form.blamountmoney.split(',').filter(item => item !== '');
            // 使用 forEach 方法将分割后的值赋给 effect 数组中每个对象的 bleffective 属性
            form.amount = form.amount.filter(item => item.blamountdate !== undefined);
            blamountdate.forEach((item, index) => {
                form.amount.push({
                    blamountdate: item,
                    blamountmoney: blamountmoney[index] || '' // 使用 || 运算符确保 blrelmoney[index] 有值，否则为 ''
                });
            });
            // 部门
            let blname = form.blname.split(',').filter(item => item !== '');
            let blproposedmoney = form.blproposedmoney.split(',').filter(item => item !== '');
            let bldeptnum = form.bldeptnum.split(',').filter(item => item !== '');
            // 使用 forEach 方法将分割后的值赋给 effect 数组中每个对象的 bleffective 属性
            form.dept = form.dept.filter(item => item.blname !== '');
            blname.forEach((item, index) => {
                form.dept.push({
                    blname: item,
                    blproposedmoney: blproposedmoney[index] || '', // 使用 || 运算符确保 blrelmoney[index] 有值，否则为 ''
                    bldeptnum: bldeptnum[index] || ''
                });
            });
            // console.log('form改变后的表单:', form)
            getFile(data.blagreementid);
        }
        form.fileList = []
        visible.value = true;
        // console.log('查看的form:', form)
        nextTick(() => {
            formRef.value.clearValidate();
        });
        title.value = getTitle()
    }
    // ============查看modal =======
    function showViewModal(data) {
        Object.assign(form, formDefault);
        if (data.blagreementid && !_.isEmpty(data)) {
            Object.assign(form, data);
            console.log('form:', form)
            form.blusenum = form.blusenum.split(',').filter(item => item !== '');
            // 协议
            let ffective = form.bleffective.split(',').filter(item => item !== '');
            let blrelmoney = form.blrelmoney.split(',').filter(item => item !== '');
            // 使用 forEach 方法将分割后的值赋给 effect 数组中每个对象的 bleffective 属性
            form.effect = form.effect.filter(item => item.bleffective !== undefined);
            ffective.forEach((item, index) => {
                form.effect.push({
                    bleffective: item,
                    blrelmoney: blrelmoney[index] || '' // 使用 || 运算符确保 blrelmoney[index] 有值，否则为 ''
                });
            });
            // 到账
            let blamountdate = form.blamountdate.split(',').filter(item => item !== '');
            let blamountmoney = form.blamountmoney.split(',').filter(item => item !== '');
            // 使用 forEach 方法将分割后的值赋给 effect 数组中每个对象的 bleffective 属性
            form.amount = form.amount.filter(item => item.blamountdate !== undefined);
            blamountdate.forEach((item, index) => {
                form.amount.push({
                    blamountdate: item,
                    blamountmoney: blamountmoney[index] || '' // 使用 || 运算符确保 blrelmoney[index] 有值，否则为 ''
                });
            });
            // 部门
            let blname = form.blname.split(',').filter(item => item !== '');
            let blproposedmoney = form.blproposedmoney.split(',').filter(item => item !== '');
            let bldeptnum = form.bldeptnum.split(',').filter(item => item !== '');
            // 使用 forEach 方法将分割后的值赋给 effect 数组中每个对象的 bleffective 属性
            form.dept = form.dept.filter(item => item.blname !== '').filter(item => item !== '');
            blname.forEach((item, index) => {
                form.dept.push({
                    blname: item,
                    blproposedmoney: blproposedmoney[index] || '', // 使用 || 运算符确保 blrelmoney[index] 有值，否则为 ''
                    bldeptnum: bldeptnum[index] || ''
                });
            });

            // console.log('form改变后的表单:', form)
            getFile(data.blagreementid);
        }
        canEdit.value = true;
        visible.value = true;
        nextTick(() => {
            formRef.value.clearValidate();
        });
        title.value = getTitle()

    }
    // 多项表单操作
    const removeUser = (item, value) => {
        if (value === 1) {
            const effectindex = form.effect.indexOf(item);
            if (effectindex !== -1) {
                if (form.effect.length == 1) {
                    message.warning("至少填写一项信息");
                } else {
                    form.effect.splice(effectindex, 1);
                }
            }
        }
        if (value === 2) {
            const index = form.amount.indexOf(item);
            if (index !== -1) {
                if (form.amount.length == 1) {
                    message.warning("至少填写一项信息");
                } else {
                    if (form.amount.length <= form.blcycle) {
                        message.warning("期数为" + form.blcycle + "，至少填写" + form.blcycle + "项信息");

                    } else {
                        form.amount.splice(index, 1);
                    }
                }
            }
        }
        if (value === 3) {
            const indexdept = form.dept.indexOf(item);
            if (indexdept !== -1) {
                if (form.dept.length == 1) {
                    message.warning("至少填写一项信息");
                } else {
                    form.dept.splice(indexdept, 1);
                }
            }
        }


    };
    const addUser = (value) => {
        if (value === 1) {
            form.effect.push({
                bleffective: undefined,//协议生效年份
                blrelmoney: undefined,//协议生效金额
                id: Date.now(),
            });
        }
        if (value === 2) {
            if (form.blcycle == undefined || form.blcycle == null || form.blcycle == '') {
                message.warning("请填写期数");
            } else {
                if (form.amount.length < form.blcycle) {
                    form.amount.push({
                        blamountdate: undefined,//到账日期
                        blamountmoney: '',//到账金额
                        id: Date.now(),
                    });
                } else {
                    message.warning("到账期数不能超过协议期数");
                }
            }
        }
        if (value === 3) {
            form.dept.push({
                blname: undefined,//部门名称
                blproposedmoney: undefined,//部门金额
                id: Date.now(),
            });
        }
    };
    //  协议文件列表
    const typeOneArray = ref("");
    // 获取文件  
    async function getFile(id) {
        try {
            let viewFile = await AgreeApi.getIdsFile(id);
            const viewFileList = viewFile.blagreement
            let arr = [viewFileList];
            typeOneArray.value = arr
        } catch (e) {
            smartSentry.captureError(e);
        } finally {

        }
    }
    // ==================文件上传=============
    const fileList = ref([]);
    const headers = {
        "Authorization": `Bearer ${useUserStore().getToken}`,
    };
    const beforeUpload = file => {
        return new Promise((resolve, reject) => {
            const fileType = file.name.replace(/.+\./, '');
            const fileFormat =
                fileType === 'pdf' ||
                fileType === 'docx' ||
                fileType === 'doc'
            const fileSize = file.size !== 0;

            if (!fileFormat) {
                message.error('只能上传pdf、docx和doc格式文件!');
                return false
            }
            const isLt2M = file.size / 1024 / 1024 < 100;
            if (!isLt2M) {
                message.error('图片尺寸不能超过100MB!');
                return false
            }
            if (!fileSize) {
                form.fileList.splice(form.fileList.indexOf(file), 1);
                message.error('不能上传空文件!');
                return false;
            }
            return resolve(false)
        });
    };
    // 选择文件
    const handleChange = info => {
        let { fileList } = info
        if (form.fileList.length > 1) {
            form.fileList.splice(0, 1)
        }
        formDefault.fileList = [...fileList]
    }
    //删除当前图片
    function handleRemove(file) {
        const index = form.fileList.indexOf(file)
        const newFileList = form.fileList.slice()
        newFileList.splice(index, 1)
        form.fileList.value = newFileList
    }



    // ============新增modal =======
    function getTitle() {
        let srt = ''
        if (!form.showView) {
            if (form.blagreementid) {
                srt = '编辑'
            } else {
                srt = '新增'
            }
        } else {
            srt = '查看'
        }
        return srt
    }



    // --------------------- form 表单 ---------------------

    // 关闭弹项
    function onClose() {
        formDefault.effect = [{
            bleffective: undefined,//协议生效年份
            blrelmoney: '',//协议生效金额
        }]
        formDefault.amount = [{
            blamountdate: undefined,//到账日期
            blamountmoney: '',//到账金额
        }]
        formDefault.dept = [{
            blname: '',//部门名称
            blproposedmoney: '',//部门金额
        }]
        Object.assign(form, formDefault);
        form.fileList = []
        delete form.showView;
        visible.value = false;
        canEdit.value = false;
    }
    // 邮箱正则
    const regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;

    // --------------------- 表单 ---------------------

    //  组件
    const formRef = ref();
    //  组件
    const formRefEffect = ref();

    const formDefault = {
        blagreementid: undefined,
        blagreementname: undefined,//协议名称
        blagreementnum: undefined,//协议编号
        blprojectid: undefined,//所属项目 id
        blprojectname: undefined,//所属项目名称
        blprojectnum: undefined,//所属项目编号
        blmoney: undefined,//金额
        blcycle: undefined,//期数
        bldonorid: undefined,//捐赠方
        bldonor: undefined,//捐赠方mingc
        bllinkmanid: undefined,//联系人
        bllinkmanname: undefined,//联系人名称
        blfollowid: undefined,//执行方
        blfollowname: undefined,//执行方
        blregist: undefined,//协议签订日期
        blproperty: undefined,//是否限定  0非限定  1 限定
        bldescription: undefined, //说明
        effect: [{
            bleffective: undefined,//协议生效年份
            blrelmoney: '',//协议生效金额
        }],
        amount: [{
            blamountdate: undefined,//到账日期
            blamountmoney: '',//到账金额
        }],
        dept: [{
            blname: '',//部门名称
            blproposedmoney: '',//部门金额
            bldeptnum: '',//部门编号
        }],
        bleffective: undefined,//协议生效年份
        blrelmoney: undefined,//协议生效金额

        blamountdate: undefined,//到账日期
        blamountmoney: undefined,//到账金额

        blname: undefined,//部门名称
        blproposedmoney: undefined,//部门金额
        bldeptnum: undefined,//部门编号

        blusenum: undefined,//用途编号
        bluse: undefined,//用途名称
        blpersonphotopath: undefined,//协议上传地址

        fileList: []//文件列表
    };

    let form = reactive({ ...formDefault });
    // 期数和到账金额期数相同
    // 期数和到账金额期数相同
    watch(
        [() => form.blcycle, () => form.blagreementid],
        ([newblcycle, newblagreementid], [Oldblcycle, oldblagreementid]) => {
            // 查看表单数据
            if (newblagreementid !== undefined) {
                if (newblcycle === null) {
                    form.amount = [{
                        blamountdate: undefined,//到账日期
                        blamountmoney: '',//到账金额
                        id: Date.now(),
                    }]
                } else if (newblcycle !== Oldblcycle && Oldblcycle !== undefined) {
                    form.amount = Array.from({ length: newblcycle }, () => ({
                        blamountdate: undefined,
                        blamountmoney: '',
                        id: Date.now(),
                    }));
                }
            } else {
                // 确保有一项
                if (newblcycle == null) {
                    form.amount = [{
                        blamountdate: undefined,//到账日期
                        blamountmoney: '',//到账金额
                        id: Date.now(),
                    }]
                } else if (Oldblcycle == undefined || newblcycle !== Oldblcycle && newblcycle !== null) {
                    form.amount = Array.from({ length: newblcycle }, () => ({
                        blamountdate: undefined,
                        blamountmoney: '',
                        id: Date.now(),
                    }));
                }
            }
        })

    const rules = {
        blagreementname: [{ required: true, message: '请输入协议名称' }],
        blagreementnum: [{ required: false, message: '请输入协议编号' }],
        blprojectnum: [{ required: true, message: '请选择所属项目' }],
        blmoney: [{ required: true, message: '请输入金额' }],
        blcycle: [{ required: true, message: '请输入期数' }],

        bldonorid: [{ required: true, message: '请选择捐赠方' }],
        bllinkmanid: [{ required: true, message: '请选择联系方' }],
        blfollowid: [{ required: true, message: '请选择执行方' }],

        blregist: [{ required: true, message: '请选择协议签订日期' }],
        blproperty: [{ required: true, message: '请选择是否限定' }],
        bldescription: [{ required: false, message: '请输入说明' }],


        bleffective: [{ required: true, message: '请选择协议生效年份' }],
        blrelmoney: [{ required: true, message: '请输入协议生效金额' }],


        blamountdate: [{ required: true, message: '请选择到账日期' }],
        blamountmoney: [{ required: true, message: '请输入到账金额' }],


        bldeptnum: [{ required: true, message: '请选择部门名称' }],
        blproposedmoney: [{ required: true, message: '请输入部门金额' }],

        blusenum: [{ required: true, message: '请选择资金用途' }],

        fileList: [{ required: false, message: '请选择协议' }],
    };
    const rulesEffect = {
        bleffective: [{ required: true, message: '请选择协议生效年份' }],
        blrelmoney: [{ required: true, message: '请输入协议生效金额' }],
    }

    function onSubmit() {
        formRef.value
            .validate()
            .then(async () => {
                isUpdate.value = false;
                SmartLoading.show();
                try {
                    let arrayblusenum = [form.blusenum];
                    form.blusenum = arrayblusenum.map(item => item).filter(value => value !== undefined).join(',');

                    let arraybluse = [form.bluse];
                    form.bluse = arraybluse.map(item => item).filter(value => value !== undefined).join(',');

                    form.bleffective = form.effect.map(item => item.bleffective).filter(value => value !== undefined).join(',');
                    form.blrelmoney = form.effect.map(item => item.blrelmoney).filter(value => value !== undefined).join(',');

                    form.blamountdate = form.amount.map(item => item.blamountdate).filter(value => value !== undefined || value !== '').join(',');
                    form.blamountmoney = form.amount.map(item => item.blamountmoney).filter(value => value !== undefined).join(',');

                    form.blname = form.dept.map(item => item.blname).filter(value => value !== undefined).join(',');
                    form.blproposedmoney = form.dept.map(item => item.blproposedmoney).filter(value => value !== undefined).join(',');
                    form.bldeptnum = form.dept.map(item => item.bldeptnum).filter(value => value !== undefined).join(',');

                    let newObj = {
                        ...form,
                        ...Object.fromEntries(Object.entries(form).filter(([key, value]) => !(key in formDefault)))
                    };
                    let isVaild = true
                    newObj.effect.forEach((item, index) => {
                        if (item.bleffective === undefined || item.bleffective === "" || item.bleffective === null) {
                            message.warning(`第${index + 1}项的协议生效年份不能为空`);
                            isVaild = false;
                        } else if (item.blrelmoney === "" || item.blrelmoney === undefined || item.blrelmoney === null) {
                            message.warning(`第${index + 1}项的协议生效金额不能为空`);
                            isVaild = false;
                        }
                    });
                    newObj.amount.forEach((item, index) => {
                        if (item.blamountdate === undefined || item.blamountdate === "" || item.blamountdate === null) {
                            message.warning(`第${index + 1}项的到账日期不能为空`);
                            isVaild = false;
                        } else if (item.blamountmoney === "" || item.blamountmoney === undefined || item.blamountmoney === null) {
                            message.warning(`第${index + 1}项的到账金额不能为空`);
                            isVaild = false;
                        }
                    });
                    newObj.dept.forEach((item, index) => {
                        if (item.blname === "" || item.blname === undefined || item.blname === null) {
                            message.warning(`第${index + 1}项的部门名称不能为空`);
                            isVaild = false;
                        } else if (item.blproposedmoney === "" || item.blproposedmoney === undefined || item.blproposedmoney === null) {
                            message.warning(`第${index + 1}项的部门金额不能为空`);
                            isVaild = false;
                        }
                    });
                    if (isVaild) {
                        delete newObj.effect;
                        delete newObj.amount;
                        delete newObj.dept;
                        delete newObj.fileList;
                        delete newObj.showView;
                        if (form.blagreementid) {
                            const formData = new FormData()
                            if (form.fileList.length === 0) {
                                formData.append('entity', JSON.stringify(newObj))
                            } else {
                                formData.append('file', formDefault.fileList[0].originFileObj)
                                formData.append('entity', JSON.stringify(newObj))
                            }
                            await AgreeApi.foundationUpdate(formData);
                        } else {
                            if (form.fileList.length === 0) {
                                message.warning(`请上传协议`);
                                return;
                            }
                            const formData = new FormData()
                            formData.append('file', formDefault.fileList[0].originFileObj)
                            formData.append('entity', JSON.stringify(newObj))
                            await AgreeApi.foundationAdd(formData);
                        }
                        Object.assign(form, formDefault);
                        message.success(`${form.blagreementid ? '修改' : '添加'}成功`);
                        emit('refresh');
                        onClose();
                    }

                } catch (error) {
                    smartSentry.captureError(error);
                } finally {
                    SmartLoading.hide();
                }
            })
            .catch((error) => {
                message.error('参数验证错误，请仔细填写表单数据!');
            });
    }

    // 协议所属项目
    const options = ref([])
    const proList = ref([])

    // 所属项目  onChangePro
    const onChangePro = (value, v) => {
        form.blprojectnum = value
        form.blagreementnum = value
        form.blprojectname = v.label
        const foundObject = proList.value.find(obj => obj.blprojectnum === value);
        form.blprojectid = foundObject.blprojectid
    }

    // 壿明一个空数组来存储所有值
    let allChangesArray = [];
    // 创建一个 Set 对象来存储不重复的值
    let uniqueChanges = new Set();
    // 部门 optionsDept
    const optionsDept = ref([])
    const onChangeDept = (value, index) => {
        const Obj = optionsDept.value.find(item => item.value === value);
        const newObj = {
            ...Obj,
            index: index
        };
        // 创建一个函数来根据对象动态添加到form数组中
        const addToForm = (obj) => {
            const department = {
                blname: obj.label, // 部门名称
                bldeptnum: obj.value, // 部门编号
                blproposedmoney: '', // 部门金额
            };

            // 根据对象的index确定添加的位置
            if (obj.index === form.length) {
                form.dept.push(department);
            } else {
                form.dept[obj.index] = department;
            }
        };
        addToForm(newObj)
    }
    // 项目联系人选择
    const optionsContact = ref([])
    const onChangeContact = (value, v) => {
        form.bllinkmanid = value
        form.bllinkmanname = v.label
    }
    // 执行方选择选择
    const optionsLeader = ref([])
    const onChangeLeader = (value, v) => {
        form.blfollowid = value
        form.blfollowname = v.label
    }
    // 用途维护
    const plainOptions = ref([])
    const onChangeUse = (value, v) => {
        form.blusenum = value
        const result = [];
        value.forEach((val) => {
            const option = plainOptions.value.find((opt) => opt.value === val);
            if (option) {
                result.push(option.label);
            }
        });
        form.bluse = result
    }
    // 是否限定  changeBlproperty
    const changeBlproperty = (value) => {
        form.blproperty = value
    }
    // 捐赠方  optionsBldonorid
    const optionsBldonorid = ref([])
    const onChangeBldonorid = (value, v) => {
        form.bldonorid = value
        form.bldonor = v.label
    }
    // departList  部门列表
    async function ajaxQuery() {
        try {
            let departList = await employeeApi.departList();
            const dataSource = departList.data
            optionsDept.value = dataSource.map(item => ({
                value: item.bldeptnum,
                label: item.blname
            }));

        } catch (e) {
            smartSentry.captureError(e);
        } finally {
        }
    }
    // 项目联系人  项目负责人
    async function ajaxQueryContact() {
        try {
            let departList = await ProLeaderApi.foundationNpList();
            const dataSource = departList.data
            optionsContact.value = dataSource.map(item => ({
                value: item.blleaderlistid,
                label: item.blleadername
            }));
            optionsLeader.value = dataSource.map(item => ({
                value: item.blleaderlistid,
                label: item.blleadername
            }));
        } catch (e) {
            smartSentry.captureError(e);
        } finally {

        }
    }
    // 基金用途  
    async function getAllUseList() {
        try {
            let departList = await AgreeApi.getAllUse();
            const dataSource = departList.data
            plainOptions.value = dataSource.map(item => ({
                value: item.blusenum,
                label: item.bluse
            }));


        } catch (e) {
            smartSentry.captureError(e);
        } finally {

        }
    }
    // 所有项目名称  
    async function getAllProjectList() {
        try {
            let departList = await AgreeApi.getAllProject();
            const dataSource = departList.data
            proList.value = departList.data
            options.value = dataSource.map(item => ({
                value: item.blprojectnum,
                label: item.blprojectname
            }));
        } catch (e) {
            smartSentry.captureError(e);
        } finally {

        }
    }
    // 捐赠方  
    async function getAllDonorList() {
        try {
            let departList = await AgreeApi.getAllDonor();
            const dataSource = departList.data
            optionsBldonorid.value = dataSource.map(item => ({
                value: item.bldonorid,
                label: item.bldonor
            }));
        } catch (e) {
            smartSentry.captureError(e);
        } finally {

        }
    }
    onMounted(() => {
        ajaxQuery(),
            ajaxQueryContact(),
            getAllUseList(),
            getAllProjectList(),
            getAllDonorList()
    })

</script>

<style lang="less" scoped>
    .form-width {
        width: 100% !important;
    }

    .footer {
        width: 100%;
        display: flex;
        justify-content: flex-end;
    }

    .ant-card-body {
        padding: 10px;
    }

    .ant-list .ant-list-item {
        padding: 6px 24px;
    }
</style>